//
//  DKRefreshControl.swift
//  Sina
//
//  Created by 赵柏清 on 16/8/10.
//  Copyright © 2016年 DarkZhao. All rights reserved.
//

import UIKit

// 声明一个枚举来记录状态
enum DKRefreshStatus: Int {
    /// 正常状态
    case Normal = 1
    /// 释放去加载状态--拖拽状态
    case Pulling = 2
    /// 正在加载数据
    case Loading = 3
}

class DKRefreshControl: UIControl {
    
    var scrollView: UIScrollView?
    
    var status : DKRefreshStatus = .Normal {
        didSet {
            switch status {
            case .Normal: messageLabel.text = "下拉刷新"
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.arrowImageView.transform = CGAffineTransformIdentity
                }, completion: nil)
            
            self.arrowImageView.hidden = false
            self.loadingView.stopAnimating()
            self.loadingView.hidden = true
                
            case .Pulling: messageLabel.text = "释放刷新"
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
            })
                
            case .Loading: messageLabel.text = "加载中"
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                // 让加载的view停留一下
                var inset = self.scrollView!.contentInset
                
                inset.top = inset.top + 50
                
                self.scrollView?.contentInset = inset
            })
            //隐藏箭头
            self.arrowImageView.hidden = true
            // 菊花开始转动
            self.loadingView.startAnimating()
            
            self.loadingView.hidden = false
                
            sendActionsForControlEvents(UIControlEvents.ValueChanged)
                
            }
        }
    }
    // 当要添加到父控件的时候就会调用此方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        if newSuperview is UIScrollView {
            
            scrollView = newSuperview as? UIScrollView
            
            // 给其添加KVO
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        }
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if scrollView!.dragging {
            
            if scrollView?.contentOffset.y < -140 && status == .Normal {
                status = .Pulling
            } else if scrollView?.contentOffset.y > -140 && status == .Pulling {
                status = .Normal
            }
            
        } else {
            if scrollView?.contentOffset.y < -140 && status == .Pulling {
                status = .Loading
            }
        }
        
    }
    
    func endRefresh() {
        if status == .Loading {
            
            UIView.animateWithDuration(0.25, animations: { () -> Void in

                var inset = self.scrollView!.contentInset
                
                inset.top = inset.top - 50
                
                self.scrollView?.contentInset = inset
            })
            
        }
        
        
        // 第二个,改变 文字
        status = .Normal
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: 设置UI
    private func setupUI() {
        
        backgroundColor = UIColor.yellowColor()
        
        // 设置控件的frame
        var uploadViewFrame = self.frame
        uploadViewFrame.size = CGSizeMake(UIScreen.mainScreen().bounds.size.width, 50)
        uploadViewFrame.origin.y -= 50
        self.frame = uploadViewFrame
        
        // 添加子控件
        addSubview(arrowImageView)
        addSubview(messageLabel)
        addSubview(loadingView)
        
        // 给子控件设置约束
        arrowImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(arrowImageView.snp_right).offset(10)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        loadingView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
    }
    
    // MARK: 懒加载
    private lazy var arrowImageView: UIImageView = {
        
        let img = UIImageView()
        
        img.image = UIImage(named: "tableview_pull_refresh")
        
        return img
    }()
    
    private lazy var messageLabel: UILabel = {
        
        let label = UILabel()
        
        label.text = "下拉刷新"
        
        return label
        
    }()
    
    private lazy var loadingView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)

}
